package alfred.mdp.utils;

import alfred.mdp.Majordomo;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

/**
 */
public class Utils {

    public static String asString(ByteBuffer buffer) {
        try {
            return new String(buffer.array(), Majordomo.DEFAUL_ENCODING);
        } catch (UnsupportedEncodingException e) {
        }
        return buffer.asCharBuffer().toString();
    }

    public static String asString(byte[] data) {
        try {
            return new String(data, Majordomo.DEFAUL_ENCODING);
        } catch (UnsupportedEncodingException e) {
        }
        return new String(data);
    }

    public static byte[] asByteArray(String data) {
        try {
            return data.getBytes(Majordomo.DEFAUL_ENCODING);
        } catch (UnsupportedEncodingException e) {
        }
        return data.getBytes();
    }

    public static byte[] asByteArray(int data) {
        return ByteBuffer.allocate(4).putInt(data).array();
    }

    public static int asInt(byte[] data) {
        return ByteBuffer.wrap(data).getInt();
    }

}
